import 'dart:io';

import 'package:flutter/material.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/states/states_model/user.dart';

class MobPush extends StatefulWidget {
  final Widget child;

  MobPush({this.child, Key key}) : super(key: key);

  @override
  _MobPushState createState() => _MobPushState();
}

class _MobPushState extends State<MobPush> {
  bool get isRelease => const bool.fromEnvironment("dart.vm.product");

  @override
  void initState() {
    super.initState();

    if (Platform.isIOS) {
      MobpushPlugin.setCustomNotification();
      MobpushPlugin.setAPNsForProduction(isRelease);
    }

    //上传隐私协议许可
    MobpushPlugin.updatePrivacyPermissionStatus(true);

    // 前台时不显示通知，只有后台时显示通知 仅andorid
    MobpushPlugin.setAppForegroundHiddenNotification(true);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 监听用户信息改变
    Provide.value<UserState>(context).addListener(() {
      final user = Provide.value<UserState>(context)?.info;

      // 将用户token设置为别名
      if (user?.memberToken == null) return;
      MobpushPlugin.setAlias(user.memberToken);
      
      // 将用户身份设置为标签
      if (user.memberType == 0) {
        MobpushPlugin.addTags(['user']);
      }
      if (user.memberType == 1) {
        MobpushPlugin.addTags(['anchor']);
      }
    });
  }

  @override
  void dispose() { 
    super.dispose();
    MobpushPlugin.deleteAlias();
    MobpushPlugin.cleanTags();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
